package com.vfa.vocaburay;


import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

import com.vfa.data.Category;
import com.vfa.data.Language;
import com.vfa.data.QuizName;
import com.vfa.data.QuizWordsData;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Contacts.Intents;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class LearnVocabulary extends Activity{

	private Spinner spUnit, spLanguage, spCatagory;
	private EditText etTime, etNum;
	private Button btnStart, btnPause, btnStop, btnSkip;
	private static TextView tvShowTime, tvViewWord, tvViewWordnum;
	private LinearLayout ledit, lShow;
	
	QuizWordsData quizdata;
	QuizName quiz;
	private ArrayList<QuizName> arrQuiz;
	private ArrayList<Integer> arrWordId;
	
	private int wordID;
	private int catagoryID;
	private int languageID;
	private int quizID;
	private static int time;
	private int num;
	private static Timer timerTask;
	
	private static Boolean islearning = false;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.learn_vocabulary_activity);
		System.out.println("onCreate");
		
		spUnit = (Spinner)findViewById(R.id.spinner_ChooseUnitLearn);
		spLanguage = (Spinner)findViewById(R.id.spinner_ChooseLanguage);
		spCatagory = (Spinner)findViewById(R.id.spinner_ChooseCatagory);
		etTime = (EditText)findViewById(R.id.editText_Timefor1Word);
		etNum = (EditText)findViewById(R.id.editText_NumWordLearn);
		btnStart = (Button)findViewById(R.id.button_StartLearnWord);
		btnPause = (Button)findViewById(R.id.button_PauseLearnWord);
		btnStop = (Button)findViewById(R.id.button_StopLearnWord);
		btnSkip = (Button)findViewById(R.id.button_SkipLearn);
		tvViewWord = (TextView)findViewById(R.id.textView_showWordLearn);
		tvShowTime = (TextView)findViewById(R.id.textView_ShowTimer);
		tvViewWordnum = (TextView)findViewById(R.id.textView_wordnumcurr);
		ledit = (LinearLayout)findViewById(R.id.linearLayout_set_learnword);
		lShow = (LinearLayout)findViewById(R.id.linearLayout_ShowWordToLearn);
		
		if(!islearning){
			
		}
		
		
		
		arrWordId = new ArrayList<Integer>();
		lShow.setVisibility(View.INVISIBLE);
		quizdata = new QuizWordsData(this);
		arrQuiz = new ArrayList<QuizName>();
		arrQuiz = quizdata.getAllQuizName();
		
		ArrayAdapter<QuizName> adapter;
		
		adapter = new ArrayAdapter<QuizName>(getApplicationContext(), android.R.layout.simple_spinner_item, arrQuiz);
		spUnit.setAdapter(adapter);
		
		spUnit.setOnItemSelectedListener(onSelectspUnit);
		spLanguage.setOnItemSelectedListener(onSelectspLaguage);
		spCatagory.setOnItemSelectedListener(onSelectspCatagory);
		
		onCreateWidget();
		
		btnStart.setOnClickListener(toStart);
		btnPause.setOnClickListener(toPause);
		btnStop.setOnClickListener(toStop);
		btnSkip.setOnClickListener(toSkip);
		
	}
	
	@Override
	public void onBackPressed() {
		if (islearning==true) {
			islearning = false;
			timerTask.cancel();
		}
		
		LearnVocabulary.this.finish();
		super.onBackPressed();
	}
	
	@Override
	protected void onResume() {
		
		super.onResume();
		if(islearning==true){
			ledit.setVisibility(View.INVISIBLE);
			ledit.bringToFront();
			lShow.setVisibility(View.VISIBLE);
		}
		
	}
	
	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onRestoreInstanceState(savedInstanceState);
		
		String wordOut = savedInstanceState.getString("word");
		String timeOut = savedInstanceState.getString("time");
		String numWordOut = savedInstanceState.getString("num");
		
		tvViewWord.setText(wordOut);
		tvShowTime.setText(timeOut);
		tvViewWordnum.setText(numWordOut);
		
	}
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		// TODO Auto-generated method stub
		super.onSaveInstanceState(outState);
		
		
		String wordOut = tvViewWord.getText().toString();
		String timeOut = tvShowTime.getText().toString();
		String numWordOut = tvViewWordnum.getText().toString();
		outState.putString("word", wordOut);
		outState.putString("time", timeOut);
		outState.putString("num", numWordOut);
	}
	
private android.view.View.OnClickListener toSkip = new android.view.View.OnClickListener() {
		
		@Override
		public void onClick(View v) {
			
			numtemp--;
        	j++;
        	timetemp = time;
			
		}
	};
	
	private android.view.View.OnClickListener toStart = new android.view.View.OnClickListener() {
		
		@Override
		public void onClick(View v) {
			
			if(getEdit() == 1){
				pause =false;
				islearning =true;
				numtemp=num;
				timetemp=time;
				ledit.setVisibility(View.INVISIBLE);
				ledit.bringToFront();
				lShow.setVisibility(View.VISIBLE);
				new TimeDown();
			}
			else{
				Toast.makeText(getApplicationContext(), "Please ! Check your select option ", Toast.LENGTH_SHORT).show();
				return;
			}
			
		}
	};
	
	private static boolean pause = false;
	private android.view.View.OnClickListener toPause = new android.view.View.OnClickListener(){

		@Override
		public void onClick(View v) {
			if (pause == false) {
				pause =true;
				btnPause.setText("Start");
					
			} else {
				pause=false;
				btnPause.setText("Pause");
				//timerTask.notifyAll();
			}
			
		}
		
	};
	@Override
	protected void onPause() {
		System.out.println("onPause");
		super.onPause();
	};
	
	@Override
	protected void onDestroy() {
		
		super.onDestroy();
	};
	
	@Override
	protected void onRestart() {
		System.out.println("onRestart");
		super.onRestart();
	};
	
	private android.view.View.OnClickListener toStop = new android.view.View.OnClickListener(){

		@Override
		public void onClick(View v) {
			
			//timerTask.cancel();
			System.out.println("stop");
			if (islearning==true) {
				islearning = false;
				timerTask.cancel();
			}
//			ledit.setVisibility(View.VISIBLE);
//			System.out.println("show1");
//			lShow.setVisibility(View.INVISIBLE);
//			System.out.println("show2");
//			lShow.bringToFront();
			LearnVocabulary.this.finish();
			
			Intent intent = new Intent(getApplicationContext(), LearnVocabulary.class);
			startActivity(intent);
			//onRestart();
			
		}
		
	};
	
	private android.widget.AdapterView.OnItemSelectedListener onSelectspUnit = new android.widget.AdapterView.OnItemSelectedListener(){

		@Override
		public void onItemSelected(AdapterView<?> arg0, View view, int pos,
				long arg3) {
			//System.out.println("quiz id = "+((QuizName)spUnit.getSelectedItem()).getQuizID());
			quizID = ((QuizName)spUnit.getSelectedItem()).getQuizID();
			ArrayList<Language> arrLang = new ArrayList<Language>();
			arrLang = quizdata.getLangInQuiz(quizID);
			if(arrLang.size()>0)
			{
				spLanguage.setEnabled(true);
				ArrayAdapter<Language> adapLang;
				adapLang= new ArrayAdapter<Language>(getApplicationContext(), android.R.layout.simple_spinner_item, arrLang);
				spLanguage.setAdapter(adapLang);
			}
		}

		@Override
		public void onNothingSelected(AdapterView<?> arg0) {
			return;
			
		}
		
	};
	
	private android.widget.AdapterView.OnItemSelectedListener onSelectspLaguage = new android.widget.AdapterView.OnItemSelectedListener(){

		@Override
		public void onItemSelected(AdapterView<?> arg0, View view, int pos,
				long arg3) {
			//int idquiztemp = ((QuizName)spUnit.getSelectedItem()).getQuizID();
			languageID = ((Language)spLanguage.getSelectedItem()).getLanguageID();
			ArrayList<Category> arrCata = new ArrayList<Category>();
			
			Category catetemp = new Category();
			catetemp.setCategoryID(0);
			catetemp.setCategoryName("All");
			arrCata.add(0, catetemp);
			
			arrCata.addAll(quizdata.getCataInLang(quizID , languageID));
			if(arrCata.size()>0)
			{
				spCatagory.setEnabled(true);
				ArrayAdapter<Category> adapCata;
				adapCata=new ArrayAdapter<Category>(getApplicationContext(), android.R.layout.simple_spinner_item, arrCata);
				spCatagory.setAdapter(adapCata);
			}
			
		}

		@Override
		public void onNothingSelected(AdapterView<?> arg0) {
			return;
			
		}
		
	};
	
	private android.widget.AdapterView.OnItemSelectedListener onSelectspCatagory = new android.widget.AdapterView.OnItemSelectedListener(){

		@Override
		public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {
			if(spCatagory.getSelectedItemPosition()==0){
				catagoryID =-1;}
			else
			{
				catagoryID = ((Category)spCatagory.getSelectedItem()).getCategoryID();
			}
			getLisWordInCata(quizID, languageID, catagoryID);
			btnStart.setEnabled(true);
			System.out.println("category id = " + catagoryID);
			
		}

		@Override
		public void onNothingSelected(AdapterView<?> arg0) {
			return;
			
		}
		
	};
	
	private void onCreateWidget(){
		spLanguage.setEnabled(false);
		spCatagory.setEnabled(false);
		btnStart.setEnabled(false);
	}

	
	private int getEdit(){
		try{
			//quizID = ((QuizName)spUnit.getSelectedItem()).getQuizID();
			
			//getListWord(quizID);
			
			if(etTime.getText().toString().trim().equals("")){
				time = Integer.parseInt(etTime.getHint().toString());
				//System.out.println("hint = "+time);
			}else{
				time = Integer.parseInt(etTime.getText().toString());
				//System.out.println("text = "+time);
			}
			if(etNum.getText().toString().trim().equals("")){
				num = arrWordId.size();
				//System.out.println("arrworId = "+num);
			}else {
				num = Integer.parseInt(etNum.getText().toString());
				//System.out.println("text = "+num);
				if(num>arrWordId.size() ||num <1)
				{
					num=arrWordId.size();
					//System.out.println("arrworId = "+num);
				}
			}
			
			return 1;
		}
		catch (Exception e) {
			return -1;
		}
			
	}
	private void getLisWordInCata(int quizid, int langid, int categoryid){
		arrWordId = quizdata.getAllWord(quizid, langid, categoryid);
		
	}
	
	private void getListWord(int Unitid){
		arrWordId = quizdata.getAllQuizWord(Unitid);
	}

	private void ShowWord(int wordID){
		String word;
		word= quizdata.getWordByID(wordID);
		tvViewWord.setText(""+ word);
	}
	
	private void show(int num){
		if(arrWordId.size()>0)
    		ShowWord(arrWordId.get(num));
	}
	private static int j=0;
	private static int numtemp;
	private static int timetemp;
	class DisplayCountdown extends TimerTask {
		
        public void run() {
        	if(numtemp>0){
        		//System.out.println(numtemp);
        		refreshWord.sendMessage(new Message());
        	}
	            if (timetemp > 0 && numtemp>0) {
	                refreshTextHandler.sendMessage(new Message());
	                if(pause ==false)
	                {
		                	timetemp--;
		                
		               System.out.println(timetemp);
		                if(timetemp == 0&& j<num-1)  {
		                	numtemp--;
		                	j++;
		                	timetemp = time;
			            }
	                }
	            } 
        }
        
    }
	
	public class TimeDown {

        public TimeDown() {

            timerTask = new Timer();
            timerTask.schedule(new DisplayCountdown(), 0, 1000);

        }

    }
	
	final Handler refreshWord = new Handler(){
		public void handleMessage(Message msg) {
			if(arrWordId.size()>0)
			{
	    		ShowWord(arrWordId.get(j));
	    		tvViewWordnum.setText((j+1)+"/"+num);
			}
		}
	};
	
	final Handler refreshTextHandler = new Handler() {
        public void handleMessage(Message msg) {
        	int minutes = timetemp / 60;
            int seconds = timetemp % 60;
            String minutesText = "";
            String secondsText = ""; 
            if (minutes == 0 && seconds < 30) {
            	tvShowTime.setTextColor(Color.RED);
            }
            // change time
            if (minutes < 10)
                minutesText = "0" + minutes;
            else
                minutesText = "" + minutes;
            if (seconds < 10)
                secondsText = "0" + seconds;
            else
                secondsText = "" + seconds;
            
            tvShowTime.setText(minutesText + ":" + secondsText);

        }
    };
}
